<template>
  <el-container v-show="showTable">
    <el-container style="display: flex; justify-content: center; height: 100%;">
      <el-card class="box-card">
        <el-form :model="searchForm" inline class="search-form">
          <el-row :gutter="20" type="flex" justify="space-between" align="middle">
            <el-col :span="12">
              <el-form-item label="">
                <el-input v-model="searchForm.projectName" placeholder="项目名称"></el-input>
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="search">
                  <Search class="button-icon" />查询
                </el-button>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item class="text-right">
                <div class="export-buttons">
                  <el-button type="success" @click="exportTeamRegistrations">
                    <Share class="button-icon" />按全部报名信息导出Excel
                  </el-button>
                  <el-button type="success" @click="exportRegistrationData">
                    <Share class="button-icon" />导出队伍难度数据Excel表格
                  </el-button>
                  <el-button type="success" @click="exportDifficultyByProject">
                    <Share class="button-icon" />按项目导出难度和内容信息
                  </el-button>
                  <el-button type="success" @click="exportDifficultyByTeam">
                    <Share class="button-icon" />按全部队伍基本信息导出
                  </el-button>
                </div>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <el-table :data="pagedTableData" style="width: 100%" stripe class="border-table">
          <el-table-column prop="id" label="序号" width="50"></el-table-column>
          <el-table-column prop="projectName" label="项目名称"></el-table-column>
          <el-table-column prop="projectGroup" label="项目组别"></el-table-column>
          <el-table-column label="项目报名情况">
            <template #default="{ row }">
            <el-button type="primary" @click="openTeamDialog(row.id)">该项目申报队伍</el-button>
            </template>
          </el-table-column>
          <el-table-column label="启用编码组">
            <template #default="{ row }">
              <span v-if="row.encodeId">{{ getEncodeName(row.encodeId) }}</span>
              <el-button v-else link >暂无启用组</el-button>
            </template>
          </el-table-column>
          <el-table-column label="操作">
            <template #default="{ row }">
              <el-button :bg="true" link @click="editRow(row)">启用组</el-button>
              <el-button :bg="true" link @click="deleteRow(row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination class="end" @size-change="handleSizeChange" @current-change="handleCurrentChange"
          :current-page="currentPage" :page-sizes="[6, 10, 20, 50]" :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper" :total="tableData.length">
        </el-pagination>
      </el-card>
    </el-container>
  </el-container>
  <el-dialog title="修改项目" v-model="dialogVisible" width="30%" @close="resetForm">
    <p>{{ tishiproject }}</p>
    <el-form :model="editForm">
      <el-form-item label="编码组" label-width="100px">
        <el-select
        v-model="editForm.name"
        filterable
        :filter-method="filterEncodeGroups"
        placeholder="请选择编码组"
      >
        <el-option
          v-for="item in filteredCodeOptions"
          :key="item.id"
          :label="`${item.name}(${item.id})`"
          :value="item.id"
        ></el-option>
      </el-select>
    </el-form-item>
  </el-form>
  <span class="dialog-footer">
    <el-button @click="dialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="submitEdit">确 定</el-button>
  </span>
</el-dialog>
</template>

<script setup>
import { ref, onMounted,watch } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import axios from 'axios';

const dialogVisible = ref(false);
const editForm = ref({
  projectGroup: [],
  name: ''
});

const filteredCodeOptions = ref([]); // 存储过滤后的编码组数据

const projectId =ref('');

const groupOptions = ref([]);

const codeOptions = ref([]);

const router = useRouter();
const route = useRoute();

const matchid = route.query.id;

const token = localStorage.getItem('adminToken');

const showTable = ref(true);

const currentPage = ref(1);
const pageSize = ref(6); // 默认每页显示6条数据
const total = computed(() => tableData.value.length); // 总数据量

const searchForm = ref({
  projectName: ''
});

const tishiproject = ref('');

//
const tableData = ref([]);

// 计算属性，用于过滤数据
const filteredData = computed(() => {
  let data = tableData.value;
  if (searchForm.value.projectName) {
    data = data.filter(item => item.projectName.includes(searchForm.value.projectName));
  }
  return data;
});

// 计算属性，更新分页数据
const pagedTableData = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value;
  const end = start + pageSize.value;
  return filteredData.value.slice(start, end);
});

// 计算属性，用于分页
const pagedData = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value;
  const end = start + pageSize.value;
  return filteredData.value.slice(start, end);
});

const handleSizeChange = (newSize) => {
  pageSize.value = newSize;
  currentPage.value = 1; // 重置为第一页
};

const handleCurrentChange = (newPage) => {
  currentPage.value = newPage;
};

const search = () => {
  // 这里可以添加搜索的逻辑
  console.log('搜索', searchForm.value.projectName);
};

//获取所有编码组
const viewEncodeGroups = async () => {
  try {
    const response = await axios.get('http://back1.idcfengye.com:15173/teamproject/encode', {
      headers: {
        'Content-Type': 'application/json',
        Authorization: `Bearer ${token}`
      }
    }
    );
    if (response.status == 200) {
      codeOptions.value = response.data;
    }
  } catch (error) {
    console.error('Error:', error);
    ElMessage.error('查看编码组失败,重新登录尝试');
  }
};

viewEncodeGroups();

//通过getEncodeName方法使用encodeId来获取编码组名称
const getEncodeName = (encodeId) => {
  const item = codeOptions.value.find(item => item.id === encodeId);
  return item ? item.name : '';
};

//获取admin渲染页面的数据
async function selectmatchproject() {
  try {
    const response = await axios.get(`http://back1.idcfengye.com:15173/competition/project/${matchid}`, {
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${token}`
      }
    });
    if (response.status == 200) {
      fetchgroup();
      tableData.value = response.data.project;
    }
  } catch (error) {
    ElMessage.error(error.response.data.msg);
  }
}

selectmatchproject();


// 获取比赛组别
async function fetchgroup() {
  try {
    const response = await axios.get(`http://back1.idcfengye.com:15173/competition/matchgroup/${matchid}`, {
      headers: {
        'Authorization': `Bearer ${token}`
      }
    });
    groupOptions.value = response.data.matchgroup;
    const combinedGroupNames = groupOptions.value.map(group => group.groupname).join(", ");
    tableData.value = tableData.value.map(item => ({
      ...item,
      projectGroup: combinedGroupNames // 添加 projectGroup 键
    }));
  } catch (error) {
    console.error('Failed to fetch projects:', error);
  }
}

// 跳转到按全部报名信息导出Excel
const exportTeamRegistrations = () => {
  router.push({ path: '/admin/allitems',query:{ matchid:matchid } });
};

// 跳转到导出队伍难度数据Excel表格
const exportRegistrationData = () => {
  router.push({ path: '/admin/teamdifficulty',query:{ matchid:matchid } });
};

// 跳转到按项目导出难度和内容信息
const exportDifficultyByProject = () => {
  router.push({ path: '/admin/projectdifficulty',query:{ matchid:matchid } });
};

// 跳转到按全部队伍基本信息导出
const exportDifficultyByTeam = () => {
  router.push({ path: '/admin/teambasic',query:{ matchid:matchid } });
};


//点击跳转到项目报名队伍的页面
const openTeamDialog = (id) => {
 router.push({ path: '/admin/registration',query:{ projectid:id,matchid:matchid } });
};

//修改弹窗的打开方法
async function editRow(row) {
  projectId.value = row.id;
  tishiproject.value = '编辑项目：' + row.projectName;
  dialogVisible.value = true;  
}

//修改编码组上传的方法
async function submitEdit(){
  const encode = {
    encodeId:editForm.value.name
  }
  try {
    const response = await axios.put(`http://back1.idcfengye.com:15173/teamproject/project/encode/${projectId.value}`, encode , {
      headers:{
        'Authorization': `Bearer ${token}`
      }
    })   
    if (response.status == 200) {
      ElMessage.success('修改成功')
      viewEncodeGroups();
      selectmatchproject();
      dialogVisible.value = false;
    }
  }catch(error){
    console.log(error);
  }
}

// 重置表单
const resetForm = () => {
  editForm.value = {
    projectGroup: [],
    name: ''
  };
};

//删除项目
const deleteRow = (row) => {
  ElMessageBox.confirm(`确定要删除这条记录吗？`, '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    axios.delete(`http://back1.idcfengye.com:15173/competition/project/${row.id}`, {
      headers: {
        'Authorization': `Bearer ${token}`
      }
    }).then(response => {
      // 检查响应状态码
      if (response.status === 200) {
        ElMessage.success('删除成功');
        selectmatchproject(); // 假设这是一个刷新列表的方法
      } else {
        // 如果状态码不是200，可以在这里处理其他情况
        ElMessage.error('删除操作失败，状态码：' + response.status);
      }
    }).catch(error => {
      // 捕获请求错误
      console.error(error);
      ElMessage.error('删除时发生错误：' + error.message);
    });
  }).catch(() => {
    // 用户点击取消按钮
    ElMessage.info('已取消删除');
  });
};

// 模糊搜索编码组的方法
const filterEncodeGroups = (value) => {
  if (value) {
    // 使用 filter 方法进行模糊搜索
    filteredCodeOptions.value = codeOptions.value.filter(item =>
      item.name.toLowerCase().includes(value.toLowerCase())
    );
  } else {
    // 如果没有输入，则加载所有编码组
    filteredCodeOptions.value = codeOptions.value;
  }
};

// 监听搜索输入的变化
const searchQuery = ref('');
watch(searchQuery, (newQuery) => {  
  filterEncodeGroups(newQuery);
});

onMounted(() => {
  viewEncodeGroups();
  selectmatchproject();
})
</script>

<style scoped>
.back-icon {
  float: left;
  margin: 0 40px 3px 0;
}

.header-icon {
  height: 50px;
  margin: 0 8px 0 0;
}

.box-card {
  background-color: #aacec6;
  display: block;
  width: 99%;
}

.shousuo {
  float: left;
  display: none;
}

.auth-main {
  width: 100%;
}

.border-table /deep/ .el-table__body-wrapper tbody td {
  border-bottom: 1px solid #000000;
}

.border-table /deep/ .el-table__header-wrapper thead th {
  background-color: #e7e4e4;
  border-bottom: 1px solid #000000;
}

.search-form {
  margin-bottom: 20px;
}

.text-right {
  text-align: right;
  float: right;
}

.button-icon {
  height: 15px;
  margin-left: -10px;
  margin-top: auto;
}

.end {
  margin-top: 10px;
}

.export-buttons>button {
  margin-top: 5px;
}

.dialog-footer {
  text-align: right;
}
</style>